package us.fourdesign.zptjob.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;

import us.fourdesign.zptjob.Activities.R;
import us.fourdesign.zptjob.DataHolder.JobInfo;
import us.fourdesign.zptjob.http.Response;
import android.content.res.Resources;

public class PartTimeJob {
	private List<JobInfo> jobs = null;
	
	public List<JobInfo> getJobs(Resources res) {
		InputStream is = null;
		if(jobs == null) {
			jobs = new ArrayList<JobInfo>();
		}
		try {
			is = res.openRawResource(R.raw.data);
			InputStreamReader isr = new InputStreamReader(is, "utf-8");
			BufferedReader br = new BufferedReader(isr);
			StringBuffer buf = new StringBuffer();
			String line;
			while (null != (line = br.readLine())) {
				buf.append(line).append("\n");
			}
			String fileString = buf.toString();
			fileString = Response.unescape(fileString);
			JSONArray jsonArray = new JSONArray(fileString);
			int i = 0;
			while (jsonArray.get(i++) != null) {
				jobs.add(new JobInfo(jsonArray.getJSONObject(i-1)));
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e2) {
					// Swallow
				}
			}
		}
		return jobs;
	}
}
